package com.btm.mcp.business.mcp;

import com.btm.mcp.business.service.BusinessTermService;
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.SearchRequest;
import com.meilisearch.sdk.model.Searchable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Component
public class BusinessTermMcpServer {

    private final BusinessTermService businessTermService;

    public BusinessTermMcpServer(BusinessTermService businessTermService) {
        this.businessTermService = businessTermService;
    }

    @Tool(description = "根据关键词查询具体含义")
    public String searchBusinessTerm(String keyword) {
        log.info(" 搜索词：{}", keyword);
        try {
            Index index = businessTermService.getIndex();

            // 只取前三条最相关的结果
            SearchRequest searchRequest = new SearchRequest(keyword)
                    .setLimit(3);

            Searchable searchResult = index.search(searchRequest);
            ArrayList<HashMap<String, Object>> hits = searchResult.getHits();
            List<String> termList = new ArrayList<>(hits.size());

            for (HashMap<String, Object> hit : hits) {
                String termInfo = hit.get("name") + "：" + hit.get("description");
                termList.add(termInfo);
            }

            String result = StringUtils.collectionToDelimitedString(termList, "\n");
            log.info("搜索结果: \n{}", result);
            return result;
        } catch (Exception e) {
            log.error("搜索业务语意出错: {}", e.getMessage(), e);
            return "搜索业务语意出错: " + e.getMessage();
        }
    }
} 